import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LocaleService with ChangeNotifier {
  static const String _localeKey = 'locale';
  static const List<Locale> supportedLocales = [Locale('en', 'US'), Locale('zh', 'CN')];

  Locale _locale = const Locale('en', 'US');
  Locale get locale => _locale;

  Future<void> init() async {
    final prefs = await SharedPreferences.getInstance();
    final localeCode = prefs.getString(_localeKey);

    final savedLocale = _parseLocale(localeCode);

    // 获取系统首选语言
    // final systemLocale = WidgetsBinding.instance.window.locales.first;
    // final systemLanguage = systemLocale.languageCode;
    // final systemMatchedLocale = _findMatchingLocale(systemLanguage);

    // 优先级: 保存的偏好 > 系统语言 > 默认英语
    // _locale = savedLocale ?? systemMatchedLocale ?? supportedLocales.first;

    // 优先级: 保存的偏好 > 默认英语
    _locale = savedLocale ?? supportedLocales.first;
    notifyListeners();
  }

  Future<void> setLocale(Locale newLocale) async {
    if (!supportedLocales.contains(newLocale)) return;
    if (_locale == newLocale) return;

    _locale = newLocale;
    notifyListeners();

    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_localeKey, newLocale.languageCode);
  }

  Locale? _findMatchingLocale(String languageCode) {
    try {
      return supportedLocales.firstWhere((locale) => locale.languageCode == languageCode);
    } catch (e) {
      return null;
    }
  }

  Locale? _parseLocale(String? localeCode) {
    if (localeCode == null) return null;
    try {
      return supportedLocales.firstWhere((locale) => locale.languageCode == localeCode);
    } catch (e) {
      return null;
    }
  }
}
